//
//  DictionaryViewController.m
//  eBook
//
//  Created by zhy on 12-12-6.
//  Copyright (c) 2012年 zhan. All rights reserved.
//

#import "DictionaryViewController.h"
#import "NSDictionary+MutableDeepCopy.h"
#import "SVProgressHUD.h"
#import "CheckNetwork.h"

@interface DictionaryViewController ()

@end

@implementation DictionaryViewController
@synthesize SearchBar;
@synthesize DicTableView;
@synthesize DicWebView;
@synthesize wordTitle;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"menu_bg.png"]];
    UIView *leftView = [self.view viewWithTag:1];
    leftView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"menu_left.png"]];
    UIView *rightView = [self.view viewWithTag:2];
    rightView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"menu_right.png"]];
    
    UIControl *KBcontrol = [[UIControl alloc] initWithFrame:CGRectMake(0, 20, 1024, 748)];
    [KBcontrol addTarget:self action:@selector(backgroudTap) forControlEvents:UIControlEventTouchDown];
    [rightView addSubview:KBcontrol];
    [rightView sendSubviewToBack:KBcontrol];
    
    DicTableView.backgroundColor = [UIColor clearColor];
    DicTableView.delegate = self;
    DicTableView.dataSource = self;
    
    SearchBar.delegate =self;
    SearchBar.backgroundColor=[UIColor clearColor];
    [[SearchBar.subviews objectAtIndex:0]removeFromSuperview];
//    SearchBar.frame = CGRectMake(14, 45, 0, 35);
//    NSLog(@"%@",NSStringFromCGRect(SearchBar.frame));
    
    
    
//    NSString *path = [[NSBundle mainBundle] pathForResource:@"sortednames"
//                                                     ofType:@"plist"];
//    NSDictionary *dict = [[NSDictionary alloc]
//                          initWithContentsOfFile:path];
//    allNames = dict;
    
    //webview
    DicWebView.backgroundColor = [UIColor clearColor];
    DicWebView.scalesPageToFit = NO;
    DicWebView.delegate = self;
    DicWebView.scrollView.alwaysBounceVertical = NO;
    DicWebView.scrollView.bounces = NO;
    
    [DicWebView loadRequest:[NSURLRequest requestWithURL:
                            [NSURL fileURLWithPath:
                             [[NSBundle mainBundle] pathForResource:@"DicWeb" ofType:@"html"]]]];
    
    [DicWebView setUserInteractionEnabled:NO];
    
    //right content
    UIView *titleView = [rightView viewWithTag:3];
    titleView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"xkzd_title.png"]];
    
    
    [self initData];
    
}

- (void)viewDidUnload
{
    [self setSearchBar:nil];
    [self setDicTableView:nil];
    [self setDicWebView:nil];
    [self setWordTitle:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationLandscapeLeft||interfaceOrientation==UIInterfaceOrientationLandscapeRight);
}

//ios 6 rotation
-(NSUInteger)supportedInterfaceOrientations{
//    return UIInterfaceOrientationLandscapeLeft;//xcode 4.4
    return UIInterfaceOrientationMaskLandscape;//xcode 4.5
}

- (BOOL)shouldAutorotate
{
    return YES;
}

#pragma mark - Action
- (IBAction)backAction:(id)sender {
    [SVProgressHUD dismiss];
    [self dismissViewControllerAnimated:YES completion:^{}];
}

#pragma mark - Private Methods

- (void)resetSearch {
    
    names = [allNames mutableDeepCopy];
    NSMutableArray *keyArray = [[NSMutableArray alloc] init];
    [keyArray addObject:UITableViewIndexSearch];
    [keyArray addObjectsFromArray:[[allNames allKeys]
                                   sortedArrayUsingSelector:@selector(compare:)]];
    keys = keyArray;
}

- (void)handleSearchForTerm:(NSString *)searchTerm {
    NSMutableArray *sectionsToRemove = [[NSMutableArray alloc] init];
    [self resetSearch];
    
    for (NSString *key in keys) {
        NSMutableArray *array = [names valueForKey:key];
        NSMutableArray *toRemove = [[NSMutableArray alloc] init];
        
        for (NSMutableDictionary *one in array) {
            
            NSString *name = [one valueForKey:@"Word"];
            
            if ([name rangeOfString:searchTerm
                            options:NSCaseInsensitiveSearch].location == NSNotFound)
                [toRemove addObject:one];
        }
        if ([array count] == [toRemove count])
            [sectionsToRemove addObject:key];
        
        [array removeObjectsInArray:toRemove];
    }
    [keys removeObjectsInArray:sectionsToRemove];
    [DicTableView reloadData];
}

-(void) backgroudTap{
    [SearchBar resignFirstResponder];
}


-(void) initData{
    
    [SVProgressHUD showWithStatus:@"加载数据..."];
    
    dispatch_queue_t   downloadQueue = dispatch_queue_create("data downloader", NULL);
    dispatch_async(downloadQueue, ^{
        
        [self loadDataFromNet];
        
        //UIKit只能在main_queue中
        dispatch_async(dispatch_get_main_queue(), ^{
            
            NSLog(@"allname count is %d",[allNames count]);
            if ([allNames count] == 0) {
                [SVProgressHUD dismissWithError:@"加载失败！"];
                int check = CheckNetwork.check;
            } else {
                [self resetSearch];
                [DicTableView reloadData];
                
                NSIndexPath *index=[NSIndexPath indexPathForRow:0 inSection:1];
                [DicTableView selectRowAtIndexPath:index animated:YES scrollPosition:UITableViewScrollPositionBottom];
                [self tableView:DicTableView didSelectRowAtIndexPath:index];
                [SVProgressHUD dismiss];
            }
            
            
        });
    });
    dispatch_release(downloadQueue);
    
}


- (void) loadDataFromNet{
    
    NSURL *url = [NSURL URLWithString:@"http://jpkc.gdou.com/api/Api/Dict"];
    NSData *jsonData = [NSData dataWithContentsOfURL:url];
    
    if (jsonData) {
        
        NSError *error;
        NSMutableArray *result = [[NSMutableArray alloc] init];
        result = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
        NSLog(@"error:%@",error);
        
        
        NSMutableDictionary *Alldata = [[NSMutableDictionary alloc] init];
        NSMutableArray *oneKeyArray = [[NSMutableArray alloc] init];
        for (NSMutableDictionary * OneWord in result) {
            
            NSString *Character = [OneWord valueForKey:@"Character"];
            //        NSString *Description = [OneWord valueForKey:@"Description"];
            
            oneKeyArray = [Alldata valueForKey:Character];
            
            if (!oneKeyArray) {
                oneKeyArray = [[NSMutableArray alloc] init];
            }
            
            [oneKeyArray addObject:OneWord];
            
            [Alldata setObject:oneKeyArray forKey:Character];
        }
        
        NSMutableArray *array = [Alldata valueForKey:@"A"];
        
        for (int i=0;i<[array count];i++) {
            NSDictionary *oldDict = (NSDictionary *)[array objectAtIndex:i];
            
            if ([[oldDict valueForKey:@"Word"] isEqual:@"ABCD模式"]) {
                
                NSMutableDictionary *newDict = [[NSMutableDictionary alloc] init];
                [newDict addEntriesFromDictionary:oldDict];
                [newDict setObject:@"<div>A&mdash;&mdash;对象（audience）：</div> <p>阐明教学对象。例如，&ldquo;小学三年级上学期的学生&rdquo;、&ldquo;参加在职培训的技术人员&rdquo;等。</p> <div>B&mdash;&mdash;行为（behavior）：</div> <p>说明通过学习以后，学习者应能做什么（行为的变化）。描述行为的基本方法是使用一个动宾结构的短语，其中行为动词说明学习的类型，宾语则说明学习的内容。例如：&quot;操作&quot;、&quot;说出&quot;、&quot;列举&quot;、&quot;比较&quot;等都是行为动词，在它们后面加上动作的对象，就构成了学习目标中关于行为的表述。</p> <div>C&mdash;&mdash;条件（condition）：</div> <p>说明上述行为在什么条件下产生。</p> <div>D&mdash;&mdash;标准（degree）：</div> <p>规定达到上述行为的最低标准（即达到所要求行为的程度）。标准一般从行为的速度、准确性和质量三方面来确定。</p>" forKey:@"Description"];
                [array replaceObjectAtIndex:i withObject:newDict];
            }
        }
        [Alldata setObject:array forKey:@"A"];
        
        
        allNames = [Alldata mutableDeepCopy];
    }

}


-(void) setDescriptionView:(NSString *)Description{

    
    NSString *cmd = [NSString stringWithFormat:@"document.getElementById('content').innerHTML='%@';",Description];
    
    NSString *js_result = [DicWebView stringByEvaluatingJavaScriptFromString:cmd];
    
}


#pragma mark  - Table View Data Source Methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return ([keys count] > 0) ? [keys count] : 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if ([keys count] == 0)
        return 0;
    NSLog(@"keys count is %d and section is %d",[keys count],section);
    
    if (section < [keys count]) {
        NSString *key = [keys objectAtIndex:section];
        NSArray *nameSection = [names objectForKey:key];
        return [nameSection count];
    } else {
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSUInteger section = [indexPath section];
    NSUInteger row = [indexPath row];
    
    NSString *key = [keys objectAtIndex:section];
    NSArray *nameSection = [names objectForKey:key];
    
    static NSString *SectionsTableIdentifier = @"DicTabelCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:
                             SectionsTableIdentifier];

    if (cell == nil) {
        cell = [[UITableViewCell alloc]
                initWithStyle:UITableViewCellStyleDefault
                reuseIdentifier:SectionsTableIdentifier];
    }
    cell.frame = CGRectMake(0, 0, 276, 36);
    cell.textLabel.text = [[nameSection objectAtIndex:row] valueForKey:@"Word"];
    cell.textLabel.textColor = [UIColor colorWithRed:76.0/255 green:76.0/255 blue:76.0/255 alpha:1.0];
    cell.textLabel.font = [UIFont systemFontOfSize:14];
    cell.textLabel.highlightedTextColor = [UIColor colorWithRed:76.0/255 green:76.0/255 blue:76.0/255 alpha:1.0];
    
    UIView *selectedView = [[UIView alloc] initWithFrame:cell.contentView.frame];
    selectedView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"xkzd_hover.png"]];
    cell.selectedBackgroundView = selectedView;
    
    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if ([keys count] == 0)
        return nil;
    
    NSString *key = [keys objectAtIndex:section];
    if (key == UITableViewIndexSearch)
        return nil;
    return key;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
//    NSLog(@"heightForHeaderInSection");
    if ([tableView.dataSource tableView:tableView numberOfRowsInSection:section == 0]) {
        return 0;
    } else {
        return 22;
    }
}


-(UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

    if (section >0) {
        UIView* headView = [[UIView alloc] init];
        headView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"xkzd_title_bg.png"]];
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 90, 22)];
        titleLabel.text=[self tableView:tableView titleForHeaderInSection:section];
        titleLabel.textColor=[UIColor colorWithRed:33.0/255 green:109.0/255 blue:194.0/255 alpha:1.0];
        titleLabel.font = [UIFont systemFontOfSize:16];
        titleLabel.backgroundColor = [UIColor clearColor];
        [headView addSubview:titleLabel];
        
        return headView;
    }
    return nil;
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    if (isSearching)
        return nil;
    return keys;
}

- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [SearchBar resignFirstResponder];
    isSearching = NO;
    SearchBar.text = @"";
    
    [tableView reloadData];
    return indexPath;
}

-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSUInteger section = [indexPath section];
    NSUInteger row = [indexPath row];
    
    NSString *key = [keys objectAtIndex:section];
    NSArray *nameSection = [names objectForKey:key];
    
    NSString *Description= [[nameSection objectAtIndex:row] valueForKey:@"Description"];
    NSString *word= [[nameSection objectAtIndex:row] valueForKey:@"Word"];
    
    self.wordTitle.text = word;
    self.wordTitle.textColor = [UIColor colorWithRed:48.0/155 green:105.0/255 blue:174.0/255 alpha:1.0];
    [self setDescriptionView:Description];
    
}

#pragma mark -  Search Bar Delegate Methods
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    NSString *searchTerm = [searchBar text];
    [self handleSearchForTerm:searchTerm];
}

- (void)searchBar:(UISearchBar *)searchBar
    textDidChange:(NSString *)searchTerm {
    if ([searchTerm length] == 0) {
        [self resetSearch];
        [DicTableView reloadData];
        return;
    }
    [self handleSearchForTerm:searchTerm];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    isSearching = NO;
    searchBar.text = @"";
    [self resetSearch];
    [DicTableView reloadData];
    [searchBar resignFirstResponder];
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    isSearching = YES;
    [DicTableView reloadData];
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
    NSString *key = [keys objectAtIndex:index];
    if (key == UITableViewIndexSearch) {
        [tableView setContentOffset:CGPointZero animated:NO];
        return NSNotFound;
    } else
    return index;
}



@end
